package cn.hzking.gjmall.wxapi;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import cn.hzking.gjmall.app.ConfigKeys;
import cn.hzking.gjmall.constant.Constants;

import static cn.hzking.gjmall.app.Configurator.LATTE_CONFIGS;


public class WXShare {

	/** 在微信开放平台注册后拿到的appid */
	private static final String APP_ID_DEBUG = (String) LATTE_CONFIGS.get(ConfigKeys.WE_CHAT_APP_ID);//测试
	private static final String APP_ID = (String) LATTE_CONFIGS.get(ConfigKeys.WE_CHAT_APP_ID);//正式
	// secret: 3b9e1ea76d1b3e71d9e0f1344af05ce6
	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001; // 4.2以上支持发送到朋友圈

	private static WXShare instance = null;
	private static IWXAPI api = null;

	private Context mContext;

	private WXShare(Context context) {
		this.mContext = context;
	}

	/**
	 * 注册微信
	 *
	 * @param
	 * @return
	 */
	public static WXShare getInstance(Context context) {
		if (instance == null) {
			if(Constants.isDebug){//如果是debug状态
				api = WXAPIFactory.createWXAPI(context, APP_ID_DEBUG, false);
				api.registerApp(APP_ID_DEBUG);
			}else {//realse状态
				//微信分享初始化， 通过WXAPIFactory工厂，获取IWXAPI的实例
				api = WXAPIFactory.createWXAPI(context, APP_ID, false);
				api.registerApp(APP_ID);
			}
			instance = new WXShare(context);
		}

		return instance;
	}


	public  void author() {
		if(!api.isWXAppInstalled()){
			Toast.makeText(mContext,"请安装微信客户端", Toast.LENGTH_SHORT).show();
		}
		final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "wechat_sdk_demo_test";
		api.sendReq(req);

	}


	/**
	 * Transaction ID corresponding to this request.
	 * @param type
	 * @return
	 */
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}

	/**
	 * 启动微信
	 *
	 * @return
	 */
	public boolean lanuchWX() {
		return api.openWXApp();
	}

	/**
	 * 是否支持发送到朋友圈
	 *
	 * @return
	 */
	public boolean isSupportTimeLine() {
		int wxSdkVersion = api.getWXAppSupportAPI();
		if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断微信App是否已安装
	 *
	 * @return
	 */
	public boolean isWXAppInstalled() {
		try {
			return api.isWXAppInstalled();
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 处理onReq或onResp响应 在WXEntryActivity的onCreate中调用
	 *
	 * @param intent
	 * @param handler
	 */
	public void handleIntent(Intent intent, IWXAPIEventHandler handler) {
		if (api != null) {
			api.handleIntent(intent, handler);
		}
	}
	/**
	 * 微信分享网页消息
	 *
	 * @param isTimeLine
	 *            是否分享到朋友圈，false为分享给好友
	 * @param webPageUrl
	 *            网页的网址
	 * @param title
	 *            标题
	 * @param description
	 *            内容描述
	 * @param bMap
	 *            网页分享中的左侧小图片
	 */
	public void shareWebPage(boolean isTimeLine, String webPageUrl, String title, String description, Bitmap bMap) {
		if(!api.isWXAppInstalled()){
			Toast.makeText(mContext,"请安装微信客户端", Toast.LENGTH_SHORT).show();
			return;
		}
		try {
			WXWebpageObject webpage = new WXWebpageObject();
			webpage.webpageUrl = webPageUrl;
			WXMediaMessage msg = new WXMediaMessage(webpage);
			msg.title = title;
			msg.description = description;
			Bitmap thumb = bMap;
			byte[] outByteArray = WxShareUtil.compressImage2ByteArray(thumb, false);
			if (outByteArray.length / 1024 >= 32) {
				Toast.makeText(mContext, "抱歉，由于图片太大，分享失败！", Toast.LENGTH_SHORT).show();
				return;
			}
			msg.thumbData = outByteArray;

			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("webpage");
			req.message = msg;
			if (isTimeLine == false) {
				req.scene = SendMessageToWX.Req.WXSceneSession;
			} else {
				if (isSupportTimeLine()) {
					req.scene = SendMessageToWX.Req.WXSceneTimeline;
				} else {
					Toast.makeText(mContext, "您的微信版本不支持分享到朋友圈", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			api.sendReq(req);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 微信分享图片消息
	 *
	 * @param isTimeLine
	 *            是否分享到朋友圈，false为分享给好友
	 * @param bMap
	 *            图片
	 */
	public void shareImgMessage(boolean isTimeLine, Bitmap bMap) {
		try {
			if(bMap == null){
				return;
			}
			// 为保证能较为清晰的分享，先按长宽比例压缩大小，再压缩质量，直到缩略图小于32k
			final int thumb_size_height = 600;
			Bitmap bmp = bMap;
			int bitmapHeight = bmp.getHeight();
			int bitmapWidth = bmp.getWidth();
			final int thumb_size_width = bitmapWidth * thumb_size_height / bitmapHeight;
			WXImageObject imgObj = new WXImageObject(bmp);

			WXMediaMessage msg = new WXMediaMessage();
			msg.mediaObject = imgObj;
			//msg.description = "这是图片";

			Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, thumb_size_width, thumb_size_height, true);
			byte[] outByteArray = WxShareUtil.compressImage2ByteArray(thumbBmp, false);
			if (outByteArray.length / 1024 >= 32) {
				Toast.makeText(mContext, "抱歉，由于图片太大，分享失败！", Toast.LENGTH_SHORT).show();
				return;
			}
			msg.thumbData = outByteArray;// 设置缩略图  NOTE: The file size should be within 32KB.
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("img");
			req.message = msg;
			if (isTimeLine == false) {
				req.scene = SendMessageToWX.Req.WXSceneSession;
			} else {
				if (isSupportTimeLine()) {
					req.scene = SendMessageToWX.Req.WXSceneTimeline;
				} else {
					Toast.makeText(mContext, "您的微信版本不支持分享到朋友圈", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			api.sendReq(req);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 *
	 * @param text
	 * @param isTimeLine 是否分享到朋友圈，false为分享给好友
	 */
	private void shareText(String text,boolean isTimeLine) {
		// 初始化一个WXTextObject对象
		WXTextObject textObj = new WXTextObject();
		textObj.text = text;
		// 用WXTextObject对象初始化一个WXMediaMessage对象
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = textObj;   // 发送文本类型的消息时，title字段不起作用
		msg.description = "text";   // 构造一个Req
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
		req.message = msg;   // 分享或收藏的目标场景，通过修改scene场景值实现。
		// 发送到聊天界面 —— WXSceneSession
		// 发送到朋友圈 —— WXSceneTimeline
		// 添加到微信收藏 —— WXSceneFavorite
		if(isTimeLine) {
			req.scene = SendMessageToWX.Req.WXSceneTimeline;
		}else {
			req.scene = SendMessageToWX.Req.WXSceneSession;
		}
		// 调用api接口发送数据到微信
		api.sendReq(req);
	}



}
